package cn.edu.henu.team.ui_test;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.adapter.DrugListAdapter;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.diagnosticLog;
import cn.edu.henu.team.bean.drugList;
import cn.edu.henu.team.fragments.HomeActivity;
import cn.edu.henu.team.table.testResult;
import cn.edu.henu.team.ui.DrugActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.style.FontStyle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ResultActivity extends AppCompatActivity {
    private double p1, p2, p3;  //记录三种病的患病概率（数量较多时采用Map）
    private String flag1 = "", flag2 = "", flag3 = ""; //记录是否需要就医
    private boolean[] flagSelected; //接收答题结果

    //注意导的包名
    private SmartTable table;
    private TextView pingYu, result, saveData;
    private Toolbar toolbar;
    private RecyclerView mRecyclerView;
    private AlertDialog alertDialog;

    private String[] kind = {"可复性牙髓炎", "急性牙髓炎", "慢性牙髓炎", "逆行性牙髓炎", "残髓炎", "牙髓坏死", "急性根尖周炎", "慢性根尖周炎"};
    private boolean[] flagKinds = new boolean[kind.length];
    private String[] findDN = {"比较严重,建议就医", "一般情况，可自行用药"};

    private String content = "", content1 = "", content2 = "", content3 = "";    //记录系统评测寄语
    private String answer = "";
    private HashMap<String, String> mHashMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        initData();
        initView();
    }

    private void initData() {
        int listNum = getIntent().getIntExtra("totalNum", 0);
        flagSelected = getIntent().getBooleanArrayExtra("flag");
        for (int i = 0; i < 5; i++) {    //1~5统计龋病的患病概率
            if (flagSelected[i] == true) {
                p1++;
            }
        }
        p1 /= 5;
        if (p1 >= 0.6 && (flagSelected[5] || flagSelected[6])) {  //大于0.6时,6,7选中一个便需就医
            flag1 = findDN[0];
            content1 += "大概率患有龋病，请您及时就医,";
        } else {
            flag1 = findDN[1];
            content1 += "出现了龋病的部分症状，但目前症状较轻，可以不用就医,";
        }

        for (int i = 7; i < 20; i++) {  //8~20统计牙髓病患病概率
            if (flagSelected[i])
                p2++;
            if (flagSelected[7] && flagSelected[8])
                flagKinds[0] = true;
            if (flagSelected[9] && flagSelected[10])
                flagKinds[1] = true;
            if (flagSelected[11] && flagSelected[12] && flagSelected[13])
                flagKinds[2] = true;
            if (flagSelected[14] && flagSelected[15])
                flagKinds[3] = true;
            if (flagSelected[16] && flagSelected[17] && flagSelected[18])
                flagKinds[4] = true;
            if (flagSelected[19])
                flagKinds[5] = true;
        }
        p2 /= 13;
        if (p2 >= 0.66 && (flagSelected[20] || flagSelected[21] || flagSelected[22])) { //大于0.66时,选中21/22/23判定就医
            flag2 = findDN[0];
            content2 += "大概率患有牙髓炎，请及时就医,进一步确定何种牙齿疾病,";
        } else {
            flag2 = findDN[1];
            content2 += "出现了牙髓炎的部分症状，但目前症状较轻，暂时可以不用看医生,";
        }

        for (int i = 23; i < listNum - 3; i++) {  //24~27统计根尖周炎患病概率
            if (flagSelected[i]) {
                p3++;
            }
            if (flagSelected[23] && flagSelected[24] && flagSelected[25])
                flagKinds[6] = true;
            if (flagSelected[26])
                flagKinds[7] = true;
        }
        p3 /= 4;
        if (p3 >= 0.5 && (flagSelected[27] || flagSelected[28] || flagSelected[29])) {  //大于0.5时,选中28/29/30判定就医
            flag3 = findDN[0];
            content3 += "大概率患有根尖周炎，请您及时就医.";
        } else {
            flag3 = findDN[1];
            content3 += "出现了根尖周炎的部分症状，但目前的情况自行服药即可.";
        }

        mHashMap.put("龋病", flag1);
        mHashMap.put("牙髓病", flag2);
        mHashMap.put("根尖周炎", flag3);
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
                intent.putExtra("id", 0);
                startActivity(intent);
                finish();
            }
        });

        List<testResult> list = new ArrayList<>();
        table = findViewById(R.id.table);

        //加载表格数据
        list.add(new testResult("龋病", String.format("%.2f", p1 * 100) + "%", flag1));
        list.add(new testResult("牙髓病", String.format("%.2f", p2 * 100) + "%", flag2));
        list.add(new testResult("根尖周炎", String.format("%.2f", p3 * 100) + "%", flag3));

        table.setData(list);
        table.setZoom(true);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setMinTableWidth(1024);       //设置表格最小宽度
        FontStyle style = new FontStyle();
        style.setTextSize(35);
        style.setTextColor(Color.BLUE);
        table.getConfig().setContentStyle(style);       //设置表格主题字体样式
        table.getConfig().setColumnTitleStyle(style);   //设置表格标题字体样式
        table.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {     //设置隔行变色
            @Override
            public int getBackGroundColor(CellInfo cellInfo) {
                if (cellInfo.row % 2 == 1) {
                    return ContextCompat.getColor(ResultActivity.this, R.color.tableBackground);
                } else {
                    return TableConfig.INVALID_COLOR;
                }
            }
        });

        content = "您" + content1 + "而且您也" + content2 + "同时您亦" + content3;
        pingYu = findViewById(R.id.pingYu);
        pingYu.setText(content);

        if (flag1.equals(findDN[0]))
            answer += "龋病、";
        for (int i = 0; i < kind.length; i++) {
            if (flagKinds[i]) {
                answer += kind[i] + " ";
            }
        }
        if (answer.equals(""))
            answer = "恭喜您，没有患病哦";
        result = findViewById(R.id.result);
        result.setText(answer);

        saveData = findViewById(R.id.saveData);
        saveData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BmobUser.isLogin()) {
                    _User user = BmobUser.getCurrentUser(_User.class);
                    diagnosticLog mLog = new diagnosticLog();
                    mLog.setContent(content);
                    mLog.setAnswer(answer);
                    mLog.setP1(Float.parseFloat(String.format("%.3f", p1 * 100)));
                    mLog.setP2(Float.parseFloat(String.format("%.3f", p2 * 100)));
                    mLog.setP3(Float.parseFloat(String.format("%.3f", p3 * 100)));
                    if(flag1.equals("比较严重,建议就医")){
                        mLog.setFindDN1(1);
                    }else{
                        mLog.setFindDN1(0);
                    }

                    if(flag2.equals("比较严重,建议就医")){
                        mLog.setFindDN2(1);
                    }else{
                        mLog.setFindDN2(0);
                    }

                    if(flag3.equals("比较严重,建议就医")){
                        mLog.setFindDN3(1);
                    }else{
                        mLog.setFindDN3(0);
                    }

                    mLog.setUser(user); //添加一对一关联
                    mLog.setUserID(user.getObjectId());
                    mLog.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                Toast.makeText(getApplicationContext(), "测试数据保存成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), e.getErrorCode(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(getApplicationContext(), "请先登录吧", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mRecyclerView = findViewById(R.id.recyclerview);

        BmobQuery<drugList> mQuery = new BmobQuery("drugList");
        mQuery.findObjects(new FindListener<drugList>() {
            @Override
            public void done(List<drugList> list, BmobException e) {
                if (e == null) {
                    if (list.size() != 0) {

                        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
                        mRecyclerView.setLayoutManager(gridLayoutManager);
                        DrugListAdapter mDrugListAdapter = new DrugListAdapter(list, getApplicationContext());
                        mRecyclerView.setAdapter(mDrugListAdapter);

                        mDrugListAdapter.setRecyclerItemClickListener(new DrugListAdapter.OnRecyclerItemClickListener() {
                            @Override
                            public void onRecyclerItemClick(int position) {
                                //Log.e("leo", "onRecyclerItemClick: " + list.get(position).getDrug());

                                String tp = list.get(position).getKind();
                                Log.e("leo", "onRecyclerItemClick: " + tp);
                                Log.e("leo", "onRecyclerItemClick: " + mHashMap.get(tp));

                                if(list.get(position).equals("") || list.get(position) == null){
                                    String message = "点击为空，请再次点击哦";
                                    creatDialog(message);
                                }else if (mHashMap.get(tp).equals(findDN[0])) {
                                    String message = "您当前选中的药物" + list.get(position).getDrug() + "是治疗" + tp + "的，但经系统评测，此病您需就医治疗,系统暂不提供帮助，谢谢";
                                    creatDialog(message);
                                } else {
                                    Intent intent = new Intent(ResultActivity.this, DrugActivity.class);
                                    intent.putExtra("objectId", list.get(position).getObjectId());
                                    startActivity(intent);
                                }
                            }
                        });
                    }
                } else {
                    Log.e("失败信息  ", e.toString());
                }
            }
        });
    }

    public void creatDialog(String message) {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(this)
                    .setTitle("系统提示")
                    .setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
        }
        if (!alertDialog.isShowing()) {
            alertDialog.show();
        }
    }
}